package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.cache.newanswers.INewAnswersCache;
import com.conversationboard.cache.newanswers.NewAnswersCaches;
import com.conversationboard.cache.newanswers.NewAnswersThread;
import com.conversationboard.controller.blogview.BlogDataProducer;
import com.conversationboard.controller.blogview.BlogEntry;
import com.conversationboard.model.User;
import com.conversationboard.site.Site;

@WebServlet(name = "BlogViewControllerServlet", urlPatterns = "/BlogViewControllerServlet")
public class BlogViewControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -5491330616224506424L;


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");

			User user = User.get(request.getUserPrincipal());

			int boardId = Integer.parseInt(request.getParameter("boardid"));

			if (!user.canRead(boardId)) {
				return;
			}

			boolean isSiteNewAnswers = (boardId == 0);
			List<NewAnswersThread> newAnswers = new LinkedList<NewAnswersThread>();

			if (isSiteNewAnswers) {
				newAnswers = Site.getSiteNewAnswers().getAllThreads();
			} else {
				INewAnswersCache newAnswersCache = NewAnswersCaches.getInstance(boardId);
				newAnswers = newAnswersCache.getAllThreads();
			}

			BlogDataProducer producer = new BlogDataProducer();
			List<BlogEntry> blogEntries = producer.produceBlogData(user, isSiteNewAnswers, newAnswers);

			request.setAttribute("blogEntries", blogEntries);
			request.setAttribute("user", user);

			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/blogview.jsp");
			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}